package com.example.viewmodelstudio.liveData;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.widget.TextView;

import com.example.viewmodelstudio.R;

import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity4 extends AppCompatActivity {
    private TextView textView;
    private MyLiveDataViewModel myLiveDataViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);
        textView = findViewById(R.id.textView);
        myLiveDataViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(MyLiveDataViewModel.class);
        textView.setText(String.valueOf(myLiveDataViewModel.getCurrentSecond().getValue()));
        myLiveDataViewModel.getCurrentSecond().observe(this, number -> textView.setText(String.valueOf(number)));
        startTime();
    }

    private void startTime() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                //非UI线程用postValue进行数据修改
                //UI线程用setValue进行数据修改
                myLiveDataViewModel.getCurrentSecond().postValue(myLiveDataViewModel.getCurrentSecond().getValue() + 1);
            }
        }, 1000, 1000);
    }
}